<template>
    <div id="page">
        <header>
            <h1 class="logo"><a href="http://www.helloweba.net" title="返回helloweba首页">helloweba</a></h1>
        </header>
        <h2><a href="http://www.helloweba.net/javascript/621.html">在Vue框架下使用Fullcalendar</a></h2>
        <div class="main">
            <FullCalendar ref="funllCalendarRef" :options="calendarOptions"              />
        </div>
        
        <footer>
            <p>Powered by helloweba.net  允许转载、修改和使用本站的DEMO，但请注明出处：<a href="http://www.helloweba.net">www.helloweba.net</a></p>
            <p class="hidden"></p>
        </footer>
    </div>
</template>

<script>
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin from '@fullcalendar/interaction'



import '@fullcalendar/core/main.css';

export default {
    components: {
        FullCalendar
    },
    data() {
        return {
            myCalendar:null,
            calendarOptions: {
                plugins: [multiMonthPlugin,interactionPlugin],
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth,dayGridWeek,dayGridDay'
                },
                defaultDate: '2019-06-12',
                navLinks: true, // can click day/week names to navigate views
                editable:true,
            },
            calendarPlugins: [ 
                dayGridPlugin,
                interactionPlugin // needed for dateClick
            ],
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek,timeGridDay'
            },
            evnetTime: {
                hour: 'numeric',
                minute: '2-digit',
                hour12: false
            },
            calendarEvents: [ // initial event data
                { title: '部门会议', start: new Date() }
            ]
        }
    },
    mounted() {
        this.myCalendar = this.$refs.funllCalendarRef.getApi(); //获取日历Api
        window.handleCheckboxChange = this.handleCheckboxChange.bind(this);
        // this.handleGetDate()
        this.generateDatesForYear(this.year)
        this.getEventList(this.dates);
        let calendarApi = this.$refs.funllCalendarRef.getApi()
    },
    created() {

    },
    methods: {
    // 获取全年日期
    generateDatesForYear(year) {  
      const startOfYear = moment(`${year}-01-01`, 'YYYY-MM-DD');  
      const endOfYear = moment(`${year}-12-31`, 'YYYY-MM-DD').endOf('day');  
      // 先清空在加入
      this.dates = []
      let currentDate = startOfYear.clone();  
      while (currentDate.isBefore(endOfYear)) {  
        this.dates.push(currentDate.clone().format('YYYY-MM-DD')); // 使用clone()来避免在循环中修改原始moment对象  
        currentDate.add(1, 'days');  
      }  
      return this.dates
    },
    handleGetDate(){
      let num= Math.ceil(365/7)*7
      let start=new Date(moment().format('yyyy-01-01')).getDay()
      let YYYY = this.year
      let dateArr=[],time=moment().format('yyyy-01-01')
      for(let i=0;i<num;i++){
        if(i < start || time > moment( YYYY+ '-12').endOf('month').format('yyyy-MM-DD')){
                dateArr.push(0)
        }
        else{ dateArr.push(time);time=moment(time).add(1,'days').format('yyyy-MM-DD') } 
        console.log('dateArr', dateArr)
      }
    },
    // 获取节假日名
    getHoliday(date) {
      let holidayName = ''
      holidayData.forEach(item => {
        // 找出节假日并且不是补班的
        // if(date == item.HoDate && !item.HoName.includes('补班')) {
        // 找出节假日和补班的
        if(date == item.HoDate) {
          holidayName = item.HoName
        }
      })
      return holidayName
    },
    // 渲染全年的复选框 参数：dates：全年日期
    getEventList(dates) {
      // this.calendarOptions.events = []
      this.calendarOptions.events = dates.map((item, index) => {
        return {
          title: this.getHoliday(item),
          date: item, id: index, completed: false
        }
      })      
    },
    // 新增日程
    handleAdd() {
      console.log("新建事件");
      var dateStr = prompt("输入日期YYYY-MM-DD格式");
      var date = new Date(dateStr + "T00:00:00");
      if (!isNaN(date.valueOf())) {
        this.myCalendar.addEvent({
          title: "新增日程",
          start: date,
          allDay: true,
        });
      } else {
        alert("Invalid date.");
      }
    },
    // 点击日程删除
    handleDelete(info) {
      console.log('info', info)
      let event = this.myCalendar.getEventById(info.event.id);
      event.remove();
    },
    // 渲染事件内容
    renderEventContent(eventInfo) {
      const event = eventInfo.event;
      const checked = event.extendedProps.completed ? 'checked' : '';
      const id = event.id;

      return {
        html: 
        // 节假日标不同的颜色
        !event.title ?
        `
          <div class="event-box">
            <input type="checkbox" id="checkbox-${id}" ${checked} οnchange="handleCheckboxChange(event, '${id}')" />
          </div>
        `
        : 
        event.title.includes('补班') ? 
        `
          <div class="event-box">
            <input type="checkbox" id="checkbox-${id}" ${checked} οnchange="handleCheckboxChange(event, '${id}')" />
            <label class="event-title-buban" for="checkbox-${id}">${event.title}</label>
          </div>
        `
        :
        `
          <div class="event-box">
            <input type="checkbox" id="checkbox-${id}" ${checked} οnchange="handleCheckboxChange(event, '${id}')" />
            <label class="event-title" for="checkbox-${id}">${event.title}</label>
          </div>
        `
      };
    },
    // 选择复选框
    handleCheckboxChange(event, eventId) {
      const checked = event.target.checked;
      const calendarApi = this.$refs.funllCalendarRef.getApi();
      const calendarEvent = calendarApi.getEventById(eventId);

      if (calendarEvent) {
        calendarEvent.setExtendedProp('completed', checked);
      }
      this.$refs.funllCalendarRef.options.events.forEach(item => {
        if(item.id == eventId) {
          item.completed = event.target.checked
        }
      })
      console.log('this.$refs.funllCalendarRef', this.$refs.funllCalendarRef.options.events)
    },
    // 今日上一年视图
    prevYearHandl() {
      console.log('上一年')
      console.log('this.$refs.funllCalendarRef', this.$refs.funllCalendarRef)
      // this.$refs.funllCalendarRef.prevYear();
      this.myCalendar.prevYear()
      console.log('获取日期', this.myCalendar.getDate())
      // 获取当前年
      this.year = moment(this.myCalendar.getDate()).format('YYYY')
      // 获取上一年日期
      this.generateDatesForYear(this.year)
      // 移出之前的复选框
      /* this.calendarOptions.events.forEach(item => {
        let event = this.myCalendar.getEventById('checkbox-' + item.id);
        event.remove();
      }) */

      console.log('this.calendarOptions.events', this.calendarOptions.events)

      // 渲染复选框
      this.getEventList(this.dates)
    },
    // 今日下一年视图
    nextYearHandl() {
      console.log('下一年')
      console.log('this.$refs.funllCalendarRef', this.$refs.funllCalendarRef)
      this.myCalendar.nextYear();
      console.log('获取日期', this.myCalendar.getDate())
      // 获取当前年
      this.year = moment(this.myCalendar.getDate()).format('YYYY')
      // 获取下一年日期
      this.generateDatesForYear(this.year)
      // 渲染复选框
      this.getEventList(this.dates)
      this.myCalendar.render()
    },
    // 设置复选框是否勾选
    // 参数：dates：全年日期，completed：是否被选择
    setEventList(dates, completed) {
      this.calendarOptions.events = this.calendarOptions.events.map(item1 => {
        dates.forEach((item2, index) => {
          if(item1.date == item2) {
            item1.completed = completed
          }
        })
        return item1
      })
      console.log('this.calendarOptions.events', this.calendarOptions.events)
    },
    // 排除节假日和周末的日期，周末为补班的不排查
    workdayHandle() {
      // 工作日
      let workdayArr = []
      // 节假日
      let holidayDataArr = []
      // 补班日
      let holidayDataArr1 = []
      holidayData.forEach(item => {
        if(!item.HoName.includes('补班')) {
          holidayDataArr.push(item.HoDate)
        }
        if(item.HoName.includes('补班')) {
          holidayDataArr1.push(item.HoDate)
        }
      })
      this.dates.forEach(item => {
        // 找出没有节假日的日期
        if(!holidayDataArr.includes(item)) {
          workdayArr.push(item)
        }
      })
      console.log('holidayDataArr', holidayDataArr)
      console.log('workdayArr', workdayArr.filter(item => holidayDataArr1.includes(item) || (moment(item).weekday() != 0 && moment(item).weekday() != 6)))
      // 返回不是周六日及是补班日的日期
      return workdayArr.filter(item => holidayDataArr1.includes(item) || (moment(item).weekday() != 0 && moment(item).weekday() != 6))
    },
    // 全部复选框选择
    handleSelectAllButton() {
      console.log('全选')
      console.log('排查节假期和工作日的日期', this.workdayHandle())
      this.setEventList(this.workdayHandle(), true)
    },
    // 取消全部复选框选择
    handleCancelSelectAllButton() {
      console.log('取消全选')
      this.setEventList(this.dates, false)
    },
    // 获取已选择的数据
    getSelectHandle() {
      let selectArr = []
      this.calendarOptions.events.forEach(item => {
        if(item.completed) {
          selectArr.push(item)
        }
      })
      console.log('获取已选择的数据', selectArr)
    },
    handleDateClick(arg) {
            if (confirm('您是否要在' + arg.dateStr + '添加一个新的事件?')) {
                this.calendarEvents.push({ // add new event data
                  title: '新的事件',
                  start: arg.date,
                  allDay: arg.allDay
                })
            }
        },
        handleEventClick(info) {
            alert('Event: ' + info.event.title);
            //alert('Coordinates: ' + info.jsEvent.pageX + ',' + info.jsEvent.pageY);
            //alert('View: ' + info.view.type);

            // change the border color just for fun
            info.el.style.borderColor = 'red';
        }

  },

}
</script>
<style>
html {
    background: url(../assets/bg.png);
}
body {
    background: url(../assets/body_bg.gif) repeat-x;
}
header {
    box-sizing: border-box;
    width: 100%;
    height: 100px;
    padding: 10px;
    overflow: hidden;
}
.logo {
    width: 70px;
    height: 70px;
    margin: 0 auto;
    background: url(../assets/logo.png) no-repeat 0 10px;
    text-indent: -999em;
}
.logo a{
    display: block;
    width: 100%;
    height: 100%;
}

footer {
    padding-top: 20px;
    height: 60px;
    text-align: center;
}
#page p{
    text-align: center;
    line-height: 42px;
}
#page h2{
    padding-top: 20px;
    text-align: center;
    font-size: 20px;
}
.main{
    margin: 10px;
    text-align: center;
    background: #fff;
    padding: 10px;
}
</style>